<?php
require_once 'libs/aliyun_oss/autoload.php';
/**
 * Class Config
 *
 * 执行Sample示例所需要的配置，用户在这里配置好Endpoint，AccessId， AccessKey和Sample示例操作的
 * bucket后，便可以直接运行RunAll.php, 运行所有的samples
 */

use OSS\OssClient;
use OSS\Core\OssException;

/**
 * Class Common
 *
 * 示例程序【Samples/*.php】 的Common类，用于获取OssClient实例和其他公用方法
 */
class OSS_Common {
	const endpoint = Aliyun_Config::OSS_ENDPOINT;
	const accessKeyId = Aliyun_Config::ACCESS_ID;
	const accessKeySecret = Aliyun_Config::ACCESS_KEY;
	const bucket = Aliyun_Config::OSS_TEST_BUCKET;

	/**
	 * 根据Config配置，得到一个OssClient实例
	 *
	 * @return OssClient 一个OssClient实例
	 */
	public static function getOssClient(){
		try {
			$ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, true);
		} catch (OssException $e) {
			printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
			printf($e->getMessage() . "\n");
			return null;
		}
		return $ossClient;
	}

	public static function getBucketName(){
		return self::bucket;
	}

	public static function get_aliyun_domain(){
		return Aliyun_Config::OSS_ENDPOINT.'/';
	}

}
function upload_oss($uid, $field = 'file', $prefix_filename = 'hll_', $allowed_types = '*'){
	$ret = array( 'code' => 400, 'info' => '' );
	$upload_path = '/tmp/';
//	$client_name = strtolower( $_FILES[$field]['name'] );
	$filename = $prefix_filename .$uid .'_'.md5(date('YmdHis').microtime().mt_rand(10000, 99999));
	if( is_dir($upload_path) ) {
		// file upload
		$config['upload_path'] = $upload_path;
		$config['file_name'] = $filename;
		$config['allowed_types'] = $allowed_types;
		$config['max_size'] = '10240';
		$config['max_width']  = '10240';
		$config['max_height']  = '7680';
		$config['overwrite']  = TRUE;
		$CI = &get_instance();
		$CI->load->library('upload', $config);
		if ( !$CI->upload->do_upload($field) ) {
			$ret['info'] = deleteHtml($CI->upload->display_errors());
		} else {
			$file = $CI->upload->data();
			// 构建鉴权对象
			$bucket = OSS_Common::getBucketName();
			$ossClient = OSS_Common::getOssClient();
			$object = 'article/'.$file['file_name'];
			$file_path = $file['full_path'];
			//裁剪图片
            new_caijian($file_path);
			$fi_00 = get_file_info($file_path);
			$options = array();
			try {
				$res = $ossClient->uploadFile($bucket, $object, $file_path, $options);
				$etag = strtoupper(md5(file_get_contents( $file_path )));
				if($res['etag'] == '"'.$etag.'"'){
					$in_data = array(
						'uid' => $uid,
						'ctime' => time(),
						'url' =>$object,
						'tid' => 1,
						'file_ext' => $file['file_ext'],
						'file_size' => $fi_00['size'],
					);
					$attachment_id = db_insert('up_img', $in_data);
					$ret['code'] = 200;
					$ret['url'] = $object;
					$ret['id'] = $attachment_id;
				}else{
					$ret['info'] = 'md5签名失败';
				}
			} catch (OssException $e) {
				$ret['info'] = $e->getMessage();
			}
			@unlink($file['full_path']);
		}
	} else {
		$ret['info'] = '目录不存在';
	}
	return $ret;
}
function upload_pic_t($uid, $img, $forder){
	$ret = array( 'code' => 400, 'info' => '' );
    // 构建鉴权对象
    $bucket = OSS_Common::getBucketName();
    $ossClient = OSS_Common::getOssClient();
    $object = $forder.'/' . $img;
    $file_path = FCPATH.'upload/'.$forder.'/'.$img;
    $options = array();
    try {
        $res = $ossClient->uploadFile($bucket, $object, $file_path, $options);
        $etag = strtoupper(md5(file_get_contents( $file_path )));
        if($res['etag'] == '"'.$etag.'"'){
            $ret['code'] = 200;
            $ret['url'] = $object;
        }else{
            $ret['info'] = 'md5签名失败';
        }
    } catch (OssException $e) {
        $ret['info'] = $e->getMessage();
    }
    @unlink($file_path);
	return $ret;
}
function upload_pic($uid, $img, $forder){
	$ret = array( 'code' => 400, 'info' => '' );
    // 构建鉴权对象
    $bucket = OSS_Common::getBucketName();
    $ossClient = OSS_Common::getOssClient();
    $object = $forder.'/' . $img;
    $file_path = FCPATH.'upload/wx_pic/'.$img;
    $options = array();
    try {
        $res = $ossClient->uploadFile($bucket, $object, $file_path, $options);
        $etag = strtoupper(md5(file_get_contents( $file_path )));
        if($res['etag'] == '"'.$etag.'"'){
            $ret['code'] = 200;
            $ret['url'] = $object;
        }else{
            $ret['info'] = 'md5签名失败';
        }
    } catch (OssException $e) {
        $ret['info'] = $e->getMessage();
    }
    @unlink($file_path);
	return $ret;
}
function aliyun_oss_del($object){
    $bucket = OSS_Common::getBucketName();
    $ossClient = OSS_Common::getOssClient();
    try {
        $ossClient->deleteObject($bucket, $object);
    } catch (OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
}
//$objects = []
function aliyun_oss_dels($objects){
    $bucket = OSS_Common::getBucketName();
    $ossClient = OSS_Common::getOssClient();
    try {
        $ossClient->deleteObjects($bucket, $objects);
    } catch (OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
}
function aliyun_oss_get_image_url($file_name = '', $width = 0, $height = 0){
	if( $file_name ) {
        if (stripos($file_name, 'http') === 0) {
            return $file_name;
        } else {
            $t = '';
            if ($width > 0 && $height > 0) {
                $t = '?x-oss-process=image/resize,m_fixed,h_' . $height . ',w_' . $width;
            } elseif ($width > 0) {
                $t = '?x-oss-process=image/resize,w_' . $width;
            } elseif ($height > 0) {
                $t = '?x-oss-process=image/resize,h_' . $height;
            }
            return OSS_Common::get_aliyun_domain() . $file_name . $t;
        }
    }
	return '';
}

function attachment_get( $id ) {
	$ret = false;
	if( $id > 0 ) {
		$ret = db_get_obj('attachment', array( 'id' => $id ) );
	}
	return $ret;
}
function attachment_get_image_url($attachment = false, $width = 0, $height = 0, $mode = 1) {
	return $attachment && $attachment['yun_upload_time'] > 0
		? aliyun_oss_get_image_url($attachment['file_name'], $width, $height ) : false;
}

function upload_common($uid, $field = 'uf', $prefix_filename = 'bee_', $allowed_types = '*'){
    $ret = array( 'status' => false, 'info' => 'Error' );
    $upload_path = '/tmp/';
    $client_name = strtolower( $_FILES[$field]['name'] );
    $filename = $prefix_filename .date_str(time(), 'YmdHis') .'_'.md5(md5(''.microtime().rand(10000, 99999))) .'_'.$client_name;
    if( is_dir($upload_path) ) {
        // file upload
        $config['upload_path'] = $upload_path;
        $config['file_name'] = $filename;
        $config['allowed_types'] = $allowed_types;
        $config['max_size'] = '10240';
        $config['max_width']  = '10240';
        $config['max_height']  = '7680';
        $config['overwrite']  = TRUE;
        $CI = &get_instance();
        $CI->load->library('upload', $config);
        if ( !$CI->upload->do_upload($field) ) {
            $ret['info'] = deleteHtml($CI->upload->display_errors());
        } else {
            $file = $CI->upload->data();
            // 构建鉴权对象
            $bucket = OSS_Common::getBucketName();
            $ossClient = OSS_Common::getOssClient();
            $object = $file['file_name'];
            $file_path = $file['full_path'];
            $fi_00 = get_file_info($file_path);
            $options = array();
            try {
                $res = $ossClient->uploadFile($bucket, $object, $file_path, $options);
                $etag = strtoupper(md5(file_get_contents( $file_path )));
                if($res['etag'] == '"'.$etag.'"'){
                    $in_data = array(
                        'uid' => $uid,
                        'ctime' => time(),
                        'file_name' =>$object,
                        'client_name' => $file['client_name'],
                        'file_ext' => $file['file_ext'],
                        'file_type' => $file['file_type'],
                        'file_size' => $fi_00['size'],
                        'yun_upload_time' => strtotime($res['date']),
                        'yun_bucket_name' => $bucket,
                    );
                    $attachment_id = db_insert('attachment', $in_data);
                    $ret['status'] = true;
                    $ret['file_name'] = $object;
                    $ret['attachment_id'] = $attachment_id;
                }else{
                    $ret['info'] = 'md5签名失败';
                }
            } catch (OssException $e) {
                $ret['info'] = $e->getMessage();
            }
            @unlink($file['full_path']);
        }
    } else {
        $ret['info'] = '目录不存在';
    }
    return $ret;
}
